package com.qiku.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiku.entity.EduConstant;
import com.qiku.entity.User;
import com.qiku.entity.UserDTO;
import com.qiku.enums.TokenException;
import com.qiku.mapper.UserDao;
import com.qiku.service.UserService;
import com.qiku.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDTO<User> login(String phone, String password) {
        UserDTO<User> dto = new UserDTO<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        QueryWrapper<Object> wrapper = new QueryWrapper<>();
//        wrapper.eq("phone",phone);
        queryWrapper.eq(User::getPhone, phone);
        Integer count = userDao.selectCount(queryWrapper);
        if (count == 0) {
            dto.setState(TokenException.ERROR_NOT_FOUND_PHONE_CODE.getCode());
            dto.setMessage(TokenException.ERROR_NOT_FOUND_PHONE_CODE.getMsg());
            dto.setContent(null);
        } else {
            //继续验证
            queryWrapper.eq(User::getPassword, password);
            User user = userDao.selectOne(queryWrapper);
            if (user == null) {
                dto.setState(TokenException.ERROR_PASSWORD_CODE.getCode());
                dto.setMessage(TokenException.ERROR_PASSWORD_CODE.getMsg());
                dto.setContent(null);
            } else {
                //登录成功
                String token = JWTUtil.createToken(user);
                dto.setToken(token);
                dto.setContent(user);
                dto.setMessage(TokenException.LOGIN_SUCCESS_CODE.getMsg());
                dto.setState(TokenException.LOGIN_SUCCESS_CODE.getCode());
                //存入redis
                redisTemplate.opsForValue().set(token, token, 15 * 60, TimeUnit.SECONDS);
            }
        }
        return dto;
    }

    @Override
    public UserDTO<User> checkToken(String token) {
        UserDTO<User> dto = new UserDTO<>();
        int verify = JWTUtil.isVerify(token);
        switch (verify) {
            case EduConstant.TOKEN_SUCCESS_CODE:
                dto.setState(EduConstant.TOKEN_SUCCESS_CODE);
                dto.setMessage(EduConstant.TOKEN_SUCCESS);
                //解析token获取userid
                int userid = JWTUtil.pareTokenUserId(token);
                //根据id查询user
                User user = userDao.selectById(userid);
                dto.setContent(user);
                //重新生成token
                String newToken = JWTUtil.createToken(user);
                dto.setToken(newToken);
                //重新设置过期时间
                redisTemplate.opsForValue().set(newToken, newToken, 15 * 60, TimeUnit.SECONDS);
                //删除原本的token
                redisTemplate.delete(token);
                break;
            case EduConstant.TOKEN_NULL_CODE:
                dto.setState(EduConstant.TOKEN_NULL_CODE);
                dto.setMessage(EduConstant.TOKEN_ERROR1);
                break;
            case EduConstant.TOKEN_ERROR_CDOE:
                dto.setState(EduConstant.TOKEN_ERROR_CDOE);
                dto.setMessage(EduConstant.TOKEN_ERROR1);
                break;
            case EduConstant.TOKEN_TIMEOUT_CDOE:
                dto.setState(EduConstant.TOKEN_TIMEOUT_CDOE);
                dto.setMessage(EduConstant.TOKEN_TIMEOUT);
                break;
        }
        return dto;
    }

    @Override
    public UserDTO<User> loginPhoneSms(String phoneNumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phoneNumber);
        User user = userDao.selectOne(queryWrapper);
        if (null == user) {
            //手机号未注册    先去注册
            register(phoneNumber,phoneNumber,"黑黑的夜","www.baidu.com");
            return loginPhoneSms(phoneNumber);

        }
        String token = JWTUtil.createToken(user);
        UserDTO<User> dto = new UserDTO<>();
        dto.setToken(token);
        dto.setContent(user);
        dto.setState(TokenException.LOGIN_SUCCESS_CODE.getCode());
        dto.setMessage(TokenException.LOGIN_SUCCESS_CODE.getMsg());
        redisTemplate.opsForValue().set(token, token, 15 * 60, TimeUnit.SECONDS);
        return dto;

    }

    public Integer register(String phoneNumber, String password, String nickName, String headImg) {
        User user = new User();
        user.setPhone(phoneNumber);
        user.setName(nickName);
        user.setPortrait(headImg);
        return userDao.insert(user);
    }
}
